/*** 
 * @Author: your name
 * @Date: 2024-09-20 22:40:29
 * @LastEditTime: 2024-10-08 20:30:35
 * @LastEditors: your name
 * @Description: 
 * @FilePath: \utils\005_FileManager\FileManager.cpp
 * @可以输入预定的版权声明、个性签名、空行等
 */
/****************************************************************************
 * @file    FileManager.cpp
 * @brief   Implementation of the file management functions for FloraModule.
 * @details This file implements the functions for file existence checks,
 *          creating files, querying disk space, and opening file dialogs.
 *
 * @author  繁花遁
 * @date    2024-08-30
 ****************************************************************************/

#include "FileManager.h"
#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QList>
#include <algorithm>
#include <FloraLogger.h>
bool fileExists(const QString& filePath)
{
    return QFile::exists(filePath);
}

bool ensureFileExists(const QString& filePath)
{
    QString dirPath = QFileInfo(filePath).absolutePath();
    QDir dir(dirPath);

    // Create directories if they do not exist
    if (!dir.exists())
    {
        if (!dir.mkpath(dirPath))
        {
            return false;
        }
    }

    QFile file(filePath);
    if (!file.exists())
    {
        return file.open(QIODevice::WriteOnly);
    }

    return true;
}

qint64 getFreeDiskSpace(const QString& path)
{
    QStorageInfo storage(path);
    return storage.bytesAvailable();
}

QString openFileDialog(QWidget* parent, const QString& caption, const QString& filter, bool saveMode)
{
    QFileDialog dialog(parent);

    if (saveMode)
    {
        dialog.setFileMode(QFileDialog::AnyFile);
    }
    else
    {
        dialog.setFileMode(QFileDialog::ExistingFiles);
    }

    dialog.setViewMode(QFileDialog::List);
    dialog.setWindowTitle(caption);
    dialog.setNameFilter(filter);
    dialog.setFilter(QDir::Files | QDir::Dirs);

    if (dialog.exec() == QDialog::Accepted)
    {
        return dialog.selectedFiles().first();
    }

    return QString();
}

// 获取文件夹的总大小（字节）
qint64 getDirectorySize(const QString& dirPath) {
    QDir dir(dirPath);
    qint64 totalSize = 0;

    // 获取文件夹中的所有文件
    foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) {
        totalSize += fileInfo.size();
    }

    return totalSize;
}

// 删除最老的文件直到总大小低于指定阈值
void removeOldFilesIfOverSizeLimit(const QString& dirPath, qint64 maxSizeMB) {
    QDir dir(dirPath);

    // 确保路径存在
    if (!dir.exists()) {
        LOG_DEBUG << "Directory does not exist!";
        return;
    }

    // 获取文件夹总大小
    qint64 totalSize = getDirectorySize(dirPath);
    qint64 maxSizeBytes = maxSizeMB * 1024 * 1024;

    // 如果文件夹大小小于阈值，直接返回
    if (totalSize <= maxSizeBytes) {
        LOG_DEBUG << "Directory size is within the limit.";
        return;
    }

    // 获取文件信息
    QList<QFileInfo> fileList = dir.entryInfoList(QDir::Files, QDir::Time);

    // 按修改时间排序（最老的文件排在前面）
    std::sort(fileList.begin(), fileList.end(), [](const QFileInfo& a, const QFileInfo& b) {
        return a.lastModified() < b.lastModified();
    });

    // 删除文件，直到总大小小于最大值
    foreach (const QFileInfo& file, fileList) {
        if (totalSize <= maxSizeBytes) {
            break;
        }
        QFile::remove(file.filePath());
        totalSize -= file.size();
        LOG_DEBUG << "Deleted:" << file.filePath();
    }
}

void moveJpgFiles(const QString& sourcePath, const QString& destinationPath) {
    QDir sourceDir(sourcePath);
    QDir destinationDir(destinationPath);

    // 检查源路径是否存在且是目录
    if (!sourceDir.exists()) {
        qDebug() << "Source directory does not exist.";
        return;
    }

    // 创建目标目录（如果不存在的话）
    if (!destinationDir.exists()) {
        if (!destinationDir.mkpath(destinationDir.absolutePath())) {
            qDebug() << "Failed to create destination directory.";
            return;
        }
    }

    // 获取所有文件信息
    QFileInfoList fileList = sourceDir.entryInfoList(QDir::Files);
    for (const QFileInfo& fileInfo : fileList) {
        // 检查文件扩展名是否为JPG
        if (fileInfo.suffix().toLower() == "jpg") {
            QString sourceFilePath = fileInfo.absoluteFilePath();
            QString destinationFilePath = destinationDir.filePath(fileInfo.fileName());

            // 移动文件
            if (QFile::rename(sourceFilePath, destinationFilePath)) {
                qDebug() << "Moved:" << sourceFilePath << "to" << destinationFilePath;
            } else {
                qDebug() << "Failed to move:" << sourceFilePath;
            }
        }
    }
}
